//
//  PicturePickerController.swift
//  PicturePicker
//
//  Created by 刘俊 on 15/10/26.
//  Copyright © 2015年 刘俊. All rights reserved.
//

import UIKit

/// 可重用 cell
private let PicturePickerCellId = "PicturePickerCellId"
/// 当前选中照片索引
private var currentIndex = 0
/// 最大选择照片数量
private let PicturePickerMaxCount = 3

/// 照片选择控制器
class PicturePickerController: UICollectionViewController {

    /// 照片数组(用来存放照片)
    lazy var pictures = [UIImage]()
    // MARK: - 构造函数
    init() {
        super.init(collectionViewLayout: PicturePickerLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 控制器的生命周期方法
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1)
        self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: PicturePickerCellId)
        
    }
    // MARK: - UICollectionViewFlowLayout的子类
    private class PicturePickerLayout: UICollectionViewFlowLayout {
        private override func prepareLayout() {
            let cout: CGFloat = 4
            let margin: CGFloat = UIScreen.mainScreen().scale * 4
            let w = (collectionView!.bounds.width - (cout + 1) * margin) / cout

            itemSize = CGSize(width: w, height: w)
            minimumInteritemSpacing = margin
            minimumLineSpacing = margin
            
            sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin)
        }
    }
}

// MARK: UICollectionViewDataSource
extension PicturePickerController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //+1保证末尾有一个加号按钮添加照片
//        return pictures.count + (pictures.count == PicturePickerMaxCount ? 0 : 1)
         return pictures.count + (pictures.count == PicturePickerMaxCount ? 0 : 1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PicturePickerCellId, forIndexPath: indexPath) as! PicturePickerCell
//        cell.backgroundColor = UIColor.redColor()
        cell.image = (indexPath.item < pictures.count) ? pictures[indexPath.item] : nil
        cell.picturePickerDelegate = self
        
        return cell
    }
}

// MARK: - PicturePickerCellDelegate
extension PicturePickerController: PicturePickerCellDelegate{

    @objc private func picturePickerCellDidAdd(cell: PicturePickerCell) {
//        print("添加图片")
        //判断是否支持访问照片库
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            print("不允许访问照片")
            return
        }
        // 记录当前选中照片索引
        currentIndex = collectionView!.indexPathForCell(cell)!.item
        //访问相册
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
//        picker.allowsEditing = true
        // 跳转控制器
        presentViewController(picker, animated: true, completion: nil)
    }
    @objc private func picturePickerCellDidRemove(cell: PicturePickerCell) {
//        print("删除图片")
        //获取照片索引
        let indexPath = collectionView!.indexPathForCell(cell)!
        //判断图片数组是否达到上限
        if indexPath.item >= pictures.count {
            return
        }
        //删除对应数据
        pictures.removeAtIndex(indexPath.item)
        //刷新数据(动画)
        collectionView?.reloadData()
//        collectionView?.deleteItemsAtIndexPaths([indexPath])
        
    }
}
//
extension PicturePickerController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
//        print(info)
        
        // 从信息字典中获取图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let scaleImage = image.scaleToWith(600)
        //将图片添加到图片数组中
        // 判断当前选中的索引是否超出数组上限
        if currentIndex < pictures.count { //当第一次添加时会引起数组越界
            pictures[currentIndex] = scaleImage
        }else {
            pictures.append(scaleImage)
        }
        //刷新数据
        collectionView?.reloadData()
        //关闭相册控制器
        //一旦实现了代理方法，则需要用代码 dismiss 控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
}
// MARK: - PicturePickerCellDelegate代理
@objc private protocol PicturePickerCellDelegate: NSObjectProtocol {

    optional func picturePickerCellDidAdd(collectionView: PicturePickerCell)
    optional func picturePickerCellDidRemove(collectionView:PicturePickerCell)
    
}
// MARK:- Cell
private class PicturePickerCell: UICollectionViewCell {

    /// 照片选择代理
    weak var picturePickerDelegate: PicturePickerCellDelegate?
    /// 照片图像
    private var image: UIImage? {
        didSet {
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: .Normal)
            //隐藏删除按钮,使隐藏按钮不能删除
            removeButton.hidden = (image == nil)
        }
    }
    // MARK: - 监听方法
    @objc private func addPicture() {
        picturePickerDelegate?.picturePickerCellDidAdd?(self)
    }
    @objc private func removePicture() {
        picturePickerDelegate?.picturePickerCellDidRemove?(self)
    }
    
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 懒加载控件
    private lazy var addButton: UIButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    private lazy var removeButton: UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
    
}

extension PicturePickerCell {

    private func setupUI() {
    
        //添加控件
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        //设置布局
        addButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.left.equalTo(contentView.snp_left)
            make.right.equalTo(contentView.snp_right)
            make.bottom.equalTo(contentView.snp_bottom)
        }
        removeButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        //添加监听事件
        addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        removeButton.addTarget(self, action: "removePicture", forControlEvents: .TouchUpInside)
        //设置填充模式
        addButton.imageView?.contentMode = .ScaleAspectFill
    }
    
}


